package javacommon.filter;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Map;

import javacommon.util.LoginInfo;
import javacommon.util.Notes;
import javacommon.util.ResInfo;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.xml.XMLSerializer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tech15.core.service.ModuleFunctionManager;

public class AuthFilter extends HttpServlet implements Filter{
	    private static Log log = LogFactory.getLog(AuthFilter.class);
	    public static ArrayList<String> unProtectedRes = null;

	    public AuthFilter() {
	    }

	    public void init(FilterConfig filtercfg) throws javax.servlet.
	        ServletException {
	    	unProtectedRes = new ArrayList<String>();
	    	unProtectedRes.add("startpage.do");
	    	unProtectedRes.add("index.do");
	    	unProtectedRes.add("admin.do");
	    	unProtectedRes.add("member_login.do");
	    	unProtectedRes.add("member_autoLogin.do");
	    	unProtectedRes.add("member_forward.do");
	    	unProtectedRes.add("member_logout.do");
	    	unProtectedRes.add("member_timeout.do");
	    }


	    public void doFilter(ServletRequest request, ServletResponse response,FilterChain filterchain) throws java.io.IOException,
	        javax.servlet.ServletException {
	        try {
	            HttpServletRequest req = (HttpServletRequest)request;
	            HttpServletResponse resp = (HttpServletResponse)response;
	            String host = req.getContextPath();
	            String path = req.getServletPath();
	            boolean isUnprotected = isUnprotectedUrl(req);
	            if(isUnprotected){
	                filterchain.doFilter(request, response);
	                return;
	            }
	            Map<String, Object> resInfo = null;
	            LoginInfo loginInfo = (LoginInfo) req.getSession().getAttribute(Notes.LOGIN_INFO);
	            if(loginInfo != null){
	            	WebApplicationContext act = WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
	            	ModuleFunctionManager fm = (ModuleFunctionManager) act.getBean("moduleFunctionManager");
	            	boolean mark = false;
	            	/*if(loginInfo.getUserid().longValue()<0){
	            		mark = fm.isHasAdminFunction(path.substring(1));
	            	}else{
	            		mark = fm.isHasFunction(loginInfo.getUserid(),path.substring(1));
	            	}*/
	            	if(true){
	            		filterchain.doFilter(request, response);
	            	}else{
	            		resInfo = ResInfo.getResInfo("",false, false, 1, "您没有此项操作的权限！","");
		            	JsonConfig jsonConfig = new JsonConfig();
		        		JSON json = JSONSerializer.toJSON(resInfo, jsonConfig);  
		                XMLSerializer xmlSerializer = new XMLSerializer();
		                xmlSerializer.setRootName("resInfo");
		                String xml = xmlSerializer.write(json);
		                response.setContentType("application/xml;charset=UTF-8");
		                PrintWriter out = response.getWriter();
		    			out.write(xml);
	            	}
	            }else{
	            	//filterchain.doFilter(request, response);
	            	/*resInfo = ResInfo.getResInfo("",false, true, 1, "你还未登入！","");
	            	JsonConfig jsonConfig = new JsonConfig();
	        		JSON json = JSONSerializer.toJSON(resInfo, jsonConfig);  
	                XMLSerializer xmlSerializer = new XMLSerializer();
	                xmlSerializer.setRootName("resInfo");
	                String xml = xmlSerializer.write(json);
	                response.setContentType("application/xml;charset=UTF-8");
	                PrintWriter out = response.getWriter();
	    			out.write(xml);*/
	            	resp.sendRedirect(host+"/member_timeout.do");
	            }
	        } catch(Exception e) {
	            log.error("error in authorization filter", e);
	        }
	    }

	    private boolean isUnprotectedUrl(HttpServletRequest request) {
	        String url = request.getServletPath();
	        int index = url.lastIndexOf("/");
	        if(index > -1){
	            url = url.substring(index + 1);
	        }
	        for(int i = 0; i < unProtectedRes.size(); i++){
	            String temp = (String)unProtectedRes.get(i);
	            if(url.lastIndexOf(temp) > -1)
	                return true;
	        }
	        if(url.endsWith(".do")){
	            url = url + "?" +  request.getQueryString();
	            for(int i = 0; i < unProtectedRes.size(); i++){
	                String temp = (String)unProtectedRes.get(i);
	                if(url.indexOf(temp) > -1)
	                    return true;
	            }
	        }
	        return false;
	    }


	    public void destroy() {
	    }


	    public static void main(String[] args) {

//	        AuthFilter tools = new AuthFilter();
//	        tools.load("config/unprotectedurl.xml");
//	        tools.getUnprotectedResources();
	        //System.out.println(unProtectedRes.toString());

	    }
}
